import { StyleSheet, Text, View, ScrollView, TouchableOpacity, Image } from 'react-native';
import React, { useState, useEffect } from 'react';
import { useNavigation, useRoute } from '@react-navigation/native';
import { useTranslation } from 'react-i18next';
import { webSocketStore, observer, deviceStore } from '~/store';
import { NavBarHeader } from '~/components';
import { scale, px2dp, onePx, width } from '~/utils/px2dp';
import { checkDeviceVersion, clockArray } from '~/utils/deviceMenues';
import {
    getBleShock,
    getHideBloodHeartStatus,
    setHideBloodHeartStatus,
    getHeartLaserStatus,
    setHeartLaserStatus,
} from '~/utils/ble/application';

export default observer(() => {
    const { t } = useTranslation();
    const navigation: any = useNavigation();
    const router: any = useRoute();
    const { device_code } = router.params || {};
    const [show, setShow] = useState([false, false, false, false, false]);
    const { device, connectDeviceInfo, shockStatus, enableHeartAndBlood, laserPowerStatus } = deviceStore;
    const { linkSubDeviceStatus } = webSocketStore;
    const [isOldVersion, setIsOldVersion] = useState(false);
    const [isNewDevice, setIsNewDevice] = useState(false);

    // 查询是否是新法规版本
    function hasThreeDots(versionString) {
        if (typeof versionString !== 'string') {
            throw new Error('Input must be a string');
        }
        const dotCount = versionString.split('.').length - 1;
        return dotCount === 3;
    }
    const getBleState = () => {
        const { firmwareVersion } = connectDeviceInfo;
        const isConnected = linkSubDeviceStatus !== 0 || deviceStore.device.connectedDeviceStatus !== 0;
        if (!isConnected) return;
        getBleShock(router.params);
        const isNewFirmware = hasThreeDots(firmwareVersion);
        if (isNewFirmware) {
            getHideBloodHeartStatus(router.params);
            setTimeout(() => {
                getHeartLaserState();
                setIsNewDevice(true);
            }, 400);
        } else {
            setTimeout(() => {
                getHeartLaserState();
                setIsNewDevice(false);
            }, 400);
        }
    };

    // 开始查询智能激光保护协议版本
    const getHeartLaserState = () => {
        const { productModle, firmwareVersion } = connectDeviceInfo;
        var firmware_sn = firmwareVersion.substr(1);
        const result: any = checkDeviceVersion(productModle, firmware_sn);
        if (result.result < 0) {
            setIsOldVersion(true);
        } else {
            setIsOldVersion(false);
            getHeartLaserStatus(router.params);
        }
    };

    const renderBox = (txt) => {
        return (
            <View style={{ paddingTop: px2dp(24) }}>
                <View style={styles.box}>
                    <Text style={styles.box_txt}>{txt}</Text>
                </View>
                <View style={styles.bottom_box} />
            </View>
        );
    };
    const onPress = (name?: string) => {
        if (linkSubDeviceStatus == 0 && device.connectedDeviceStatus == 0) {
            Toast.show({ content: t('BleToolMenues.t15') });
            return;
        }
        navigation.navigate(name, router.params);
    };

    useEffect(() => {
        getBleState();
    }, [connectDeviceInfo.firmwareVersion]);

    const renderItem = ({ title, index, txt, img, open, callback, maskTxt = '' }) => {
        return (
            <View style={{ marginBottom: px2dp(24) }}>
                <View
                    style={{
                        position: 'absolute',
                        top: px2dp(60),
                        zIndex: 99999,
                        elevation: 99999,
                    }}>
                    {show[index] && renderBox(txt)}
                </View>
                <TouchableOpacity
                    style={styles.item}
                    onPress={() => {
                        callback && callback();
                    }}>
                    <View style={styles.top}>
                        <Text style={styles.title}>{title}</Text>
                        <TouchableOpacity
                            onPress={() => {
                                if (show[index]) return;
                                let temp = [...show];
                                temp[index] = true;
                                setShow(temp);
                                setTimeout(() => {
                                    let temp = [...show];
                                    temp[index] = false;
                                    setShow(temp);
                                }, 5000);
                            }}>
                            <Text style={styles.question}>?</Text>
                        </TouchableOpacity>
                    </View>

                    <View style={styles.center}>
                        <Image source={img} resizeMode={'contain'} style={styles.imgLeft} />
                        {open ? (
                            <View style={{ alignItems: 'center' }}>
                                <Image
                                    source={require('~/assets/deviceTools/toolOpen.png')}
                                    resizeMode={'contain'}
                                    style={styles.imgRight}
                                />
                                <Text style={styles.txtRight}>{maskTxt ? maskTxt : t('BleToolMenues.t1')}</Text>
                            </View>
                        ) : (
                            <View style={{ alignItems: 'center' }}>
                                <Image
                                    source={require('~/assets/deviceTools/toolClose.png')}
                                    resizeMode={'contain'}
                                    style={styles.imgRight}
                                />
                                <Text style={styles.txtRight}>{maskTxt ? maskTxt : t('BleToolMenues.t2')}</Text>
                            </View>
                        )}
                    </View>
                </TouchableOpacity>
            </View>
        );
    };
    return (
        <View style={styles.container}>
            <NavBarHeader title={t('BleToolMenues.title')} />
            <ScrollView showsVerticalScrollIndicator={false} contentContainerStyle={styles.contentStyle}>
                <View style={[styles.top, { flexWrap: 'wrap' }]}>
                    {renderItem({
                        title: t('BleToolMenues.t3'),
                        index: 0,
                        txt: t('BleToolMenues.t4'),
                        img: require('~/assets/deviceTools/toolBattery.png'),
                        open: true,
                        callback: () => {
                            onPress('BlePowerMode');
                        },
                    })}
                    {renderItem({
                        title: t('BleToolMenues.t5'),
                        index: 1,
                        txt: t('BleToolMenues.t6'),
                        img: require('~/assets/deviceTools/toolSleep.png'),
                        open: shockStatus,
                        callback: () => {
                            onPress('BleSleep');
                        },
                    })}
                    {clockArray.indexOf(device_code) !== -1 &&
                        (linkSubDeviceStatus !== 0 || deviceStore.device.connectedDeviceStatus !== 0) &&
                        renderItem({
                            title: t('BleToolMenues.t13'),
                            index: 1,
                            txt: t('BleToolMenues.t14'),
                            img: require('~/assets/deviceTools/colokImg.png'),
                            open: shockStatus,
                            callback: () => {
                                onPress('SetBleColock');
                            },
                        })}
                    {/* {renderItem({
                        title: t('BleToolMenues.t7'),
                        index: 2,
                        txt: t('BleToolMenues.t8'),
                        img: require('~/assets/deviceTools/laser_on.png'),
                        open: false,
                        callback: () => {
                            // this.event('LaserNew');
                        },
                    })} */}
                    {(linkSubDeviceStatus !== 0 || deviceStore.device.connectedDeviceStatus !== 0) &&
                        renderItem({
                            title: t('BleToolMenues.t7'),
                            index: 3,
                            txt: t('BleToolMenues.t9'),
                            img: require('~/assets/deviceTools/laser_on.png'),
                            open: !laserPowerStatus,
                            callback: () => {
                                if (isOldVersion) {
                                    Toast.show({ content: t('BleToolMenues.t12') });
                                } else {
                                    setHeartLaserStatus(router.params, laserPowerStatus == 0 ? 1 : 0);
                                    setTimeout(() => {
                                        getHeartLaserStatus(router.params);
                                    }, 400);
                                }
                            },
                        })}
                    {isNewDevice &&
                        renderItem({
                            title: t('BleToolMenues.t10'),
                            index: 4,
                            txt: t('BleToolMenues.t11'),
                            img: require('~/assets/deviceTools/vip.png'),
                            open: !enableHeartAndBlood,
                            callback: () => {
                                setHideBloodHeartStatus(router.params, enableHeartAndBlood ? 1 : 0);
                                setTimeout(() => {
                                    getHideBloodHeartStatus(router.params);
                                }, 400);
                            },
                        })}
                </View>
            </ScrollView>
        </View>
    );
});

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    contentStyle: {
        flexGrow: 1,
        paddingBottom: '20%',
        marginHorizontal: px2dp(24),
    },
    box: {
        width: px2dp(274),
        backgroundColor: 'rgba(112, 112, 112, 0.8)',
        borderRadius: px2dp(12),
        position: 'relative',
        padding: px2dp(24),
        justifyContent: 'center',
    },

    box_txt: {
        color: '#fff',
        fontSize: scale(28),
        lineHeight: scale(40),
    },

    bottom_box: {
        borderStyle: 'solid',
        borderTopWidth: 2,
        borderRightWidth: 5,
        borderLeftWidth: 5,
        borderBottomWidth: 2,
        borderTopColor: '#fff',
        borderLeftColor: '#fff',
        borderBottomColor: 'rgba(112, 112, 112, 0.8)',
        borderRightColor: 'rgba(112, 112, 112, 0.8)',
        position: 'absolute',
        top: 2,
        right: 0,
    },

    item: {
        backgroundColor: '#fff',
        width: (width - px2dp(70)) / 2,
        borderRadius: px2dp(24),
        padding: px2dp(24),
        height: px2dp(300),
        justifyContent: 'space-between',
        flexDirection: 'column',
    },
    top: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
    },
    title: {
        color: '#111111',
        fontSize: scale(28),
        lineHeight: px2dp(40),
        width: '90%',
    },
    center: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        marginTop: px2dp(64),
    },
    question: {
        color: '#A4A4A4',
        fontSize: scale(32),
        borderWidth: onePx,
        borderColor: '#A4A4A4',
        width: px2dp(40),
        height: px2dp(40),
        borderRadius: px2dp(20),
        textAlign: 'center',
        lineHeight: px2dp(40),
    },
    imgLeft: {
        width: px2dp(68),
        height: px2dp(64),
    },

    imgRight: {
        width: px2dp(60),
        height: px2dp(60),
    },

    txtRight: {
        fontSize: scale(24),
        color: '#666666',
        marginTop: px2dp(6),
    },
});
